package com.yuou.controller;


import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yuou.annotation.SystemLog;
import com.yuou.common.base.BlogerBaseController;
import com.yuou.model.Bloger;
import com.yuou.model.BlogerRole;
import com.yuou.model.Message;
import com.yuou.service.BlogerRoleService;
import com.yuou.service.BlogerService;
import com.yuou.service.MessageService;
import com.yuou.shiro.ShiroDbRealm;
import com.yuou.util.CipherUtil;
import com.yuou.util.ConstantUtil;
import com.yuou.util.UserIpUtil;



@Controller
public class BlogerController extends BlogerBaseController {

	@Resource(name = "blogerServiceImpl")
	private BlogerService blogerService;
	
	@Resource(name = "blogerRoleServiceImpl")
	private BlogerRoleService blogerRoleService;
	
	@Resource(name = "messageServiceImpl")
	private MessageService messageService;
	
	 /** 
     * 初始登陆界面 
     * @param request 
     * @return 
     */  
    @RequestMapping("/login")  
    public String tologin(HttpServletRequest request, HttpServletResponse response, Model model){  
    	
    	return "login";  
    }  
      
    /** 
     * 验证用户名和密码 
     * @param request 
     * @return 
     */  
    @RequestMapping(value="/checkLogin/{username}")
    @SystemLog(description = ConstantUtil.LOGIN_IN,userType=ConstantUtil.USERTYPE_ADMIN) 
    public String login(@PathVariable(value = "username") String username,String password,Model model,HttpServletRequest request) {
    	Bloger bloger = blogerService.getUserByLoginName(username);
    	String tpassword = password;
    	BlogerRole blogerRole=null;
    	if(bloger!=null) {
    		blogerRole = blogerRoleService.selectByblogerId(bloger.getId());
    	}
    	model.addAttribute("blogerRole",blogerRole);
        String result = ""; 
        //取得 密码，并用MD5加密  
        password = CipherUtil.generatePassword(CipherUtil.generatePassword(password+username));
        //System.out.println("password================"+password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
        Subject currentUser = SecurityUtils.getSubject();  
        try {  
            //if (!currentUser.isAuthenticated()){//使用shiro来验证  
                token.setRememberMe(true);  //记住密码
                currentUser.login(token);//验证角色和权限  
                //System.out.println("走了验证===========shiro");
            //}
            result = "admin/index";//验证成功  
        }  catch(LockedAccountException le) {
        	result = "login";//验证失败  
            model.addAttribute("message", "账号被冻结,请联系管理员！");
            model.addAttribute("username", username);
            model.addAttribute("password", tpassword);
        }  catch (AuthenticationException ae) {  
            result = "login";//验证失败  
            model.addAttribute("message", "用户名或密码错误");
            model.addAttribute("username", username);
            model.addAttribute("password", tpassword);
        } 
        return result;  
    }  
    
    /** 
     * 退出 
     * @return 
     */  
    @RequestMapping(value = "/admin/logout")  
    @SystemLog(description = ConstantUtil.LOGIN_OUT,userType=ConstantUtil.USERTYPE_ADMIN) 
    public String logout(ShiroDbRealm shiro) {    
        Subject currentUser = SecurityUtils.getSubject();
        String result = "login";    
        currentUser.logout();    
        return result;    
    } 
    
    /**
	  * 发送消息功能
	  * @param blog
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping(value = "/addMessage",method = RequestMethod.POST)
	 @SystemLog(description = ConstantUtil.BLOGER_UPDATE,userType=ConstantUtil.USERTYPE_ADMIN) 
	 public String addMessage(Model model,Message message,ServletRequest srequest) throws Exception{
		 System.out.println("进入此方法================");
		 HttpServletRequest request = (HttpServletRequest) srequest;
		 String ip=UserIpUtil.getIp(request);
		 message.setIp(ip);
		 message.setCreateDate(new Date());
		 String result="error/blackIp";
		 if(messageService.insertMessage(message)!=0){
			 model.addAttribute("result", "提交成功");
		 }else{
			 model.addAttribute("result", "提交失败");
		 }
		 return result;
	 }
   }
